package mobi.greenplate.client.parser;

import java.io.InputStream;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

/**
 *
 * @author dmakariev
 */
public class DomainParser<T> {

    public static <T> DomainParser<T> newInstance(DomainHandler<T> domainHandler) {
        return new DomainParser<T>(domainHandler);
    }

    private DomainParser(DomainHandler<T> domainHandler) {
        this.domainHandler = domainHandler;
    }
    private final DomainHandler<T> domainHandler;

    private DomainHandler<T> getDomainHandler() {
        return domainHandler;
    }

    public T parse(InputStream inputStream) {
        SAXParserFactory factory = SAXParserFactory.newInstance();
        try {
            SAXParser parser = factory.newSAXParser();
            DomainHandler<T> handler = getDomainHandler();
            parser.parse(inputStream, handler);
            return handler.getEntity();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
